<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array</title>
</head>

<body>
    <p>map和filter会生成新数组</p>
    <p>reduce求和、求数组项最大值、数组去重</p>
</body>
<script>
    // 1. filter()不会对空数组进行检测、不会改变原始数组
    let arr1 = [1, 2, 10, 50, 24, 99];
    let arr = [
        {
            name: "mortal",
            address: "shanghai",
            tel: 15252345524
        },
        {
            name: "mortal",
            address: "beijing",
            tel: 15252345524
        },
        {
            name: "sean",
            address: "hangzhou",
            tel: 15252345524
        }
    ]
    let res1 = arr1.filter((item) => item > 20);
    console.log("filter一维数组根据条件大于20过滤", res1); //[24,50,99]
    let res2 = arr.filter((item) => item.name == 'mortal')
    console.log("filter多维数组对象根据条件name=mortal", res2);

    //2.arr.reduce 
    // 求和
    let sum1 = arr1.reduce((prev, next) => {
        return prev + next;
    }, 0)
    console.log(arr1, "reduce求和", sum1)
    // 求数组项最大值
    let max = arr1.reduce((prev, next) => {
        return Math.max(prev, next)
    })
    console.log(arr1, "reduce求最大值", max);

    // 数组去重也可以使用new set
    let arr2 = [1, 3, 1, 4, 5, 7, 5]
    var newArr = arr2.reduce((prev, next) => {
        prev.indexOf(next) === -1 && prev.push(next);
        return prev
    }, []);
    let newArr2 = new Set(arr2)
    console.log(arr2, "reduce去重", newArr);
    console.log(arr2, "new Set去重", newArr2);

    // 3. forEach
    arr.forEach(item => {
        item.age = 18
    });
    arr1.forEach(item => {
        console.log(item)
    });
    console.log(arr1)

    // 4.map 循环遍历数组变成新数组
    let arr4 = [1, 2, 3, 4, 5, 6]
    let res4 = arr4.map(item => {
        return item += 1
    });
    console.log("map", arr4, res4)

</script>

</html>